/*
 * beep.c
 *
 *  Created on: 2017年5月4日
 *      Author: chenss
 */

#include "io/beep.h"
#include "ctimer.h"
#include "io/vibration.h"

#define _SPEAK_ON()  do{GPIO_WriteBit(GPIOB, GPIO_Pin_9, 1); _isSpeaking = TRUE;}while(0)
//#define _SPEAK_ON()  do{GPIO_WriteBit(GPIOB, GPIO_Pin_9, 0); _isSpeaking = TRUE;}while(0)
#define _SPEAK_OFF() do{GPIO_WriteBit(GPIOB, GPIO_Pin_9, 0); _isSpeaking = FALSE;}while(0)

static Ctimer_t _step, _timeout;
static bool _isSpeaking;

void Beep_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    _SPEAK_OFF();

    Beep_Set(0);
}

void Beep_OnSleep(void)
{
    Beep_Set(0);
}

static void _OnSetp(void)
{
    if(_isSpeaking)
    {
        _SPEAK_OFF();
    }
    else
    {
        _SPEAK_ON();
    }
}

static void _OnTimerout(void)
{
    Ctimer_Stop(& _step);
    Ctimer_Stop(& _timeout);
    _SPEAK_OFF();

    Vibration_Pause(FALSE);
}

/**
 *
 * @param value
 * TODO 改为使用使用定时器定时
 */
void Beep_Set(int value)
{
    if(value == 0)
    {
        Ctimer_Stop(& _step);
        Ctimer_Stop(& _timeout);
        _SPEAK_OFF();

        return;
    }

    if(! Ctimer_IsRunning(& _timeout))
    {
        Ctimer_Start(& _step, 200, _OnSetp, 0);
        Ctimer_Start(& _timeout, value * 1000, _OnTimerout, 0);
        Vibration_Pause(TRUE);
        _SPEAK_ON();
    }
    else
    {
        Ctimer_Restart(& _timeout, value * 1000);
    }

    debug("Alarm for %d second\r\n", value);
}
